//
//  OrderDetailViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/20.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "AddressManageViewController.h"
#import "LogisticsTableViewCell.h"
#import "AddressMessageCell.h"
#import "OrderStateTableViewCell.h"
#import "OrderGoodsTableViewCell.h"
#import "OrderMessageTableViewCell.h"
#import "ShopOrderDetailModel.h"
#import "EmployeeOrderDetailVC.h"
#import "SelectPayMethodsView.h"
#import "WaitCommentVC.h"

@interface OrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource,passValueDelegate>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong)SelectPayMethodsView *selectPayMethodView;
@property (nonatomic, assign) BOOL isShow;
///商城订单详情
@property (nonatomic,strong)  ShopOrderDetailModel       * shopOrderDetailModel;
@property (nonatomic, strong)AddressManageViewController * addressManageViewController;
@property (nonatomic, strong)AddressManagerDataModel     * addressDataModel;
@property (nonatomic,strong)  NSMutableArray             * shopOrderDetailArray;

@end

@implementation OrderDetailViewController

- (NSMutableArray *)shopOrderDetailArray
{
    if (_shopOrderDetailArray == nil) {
        _shopOrderDetailArray = [[NSMutableArray alloc] init];
    }
    return _shopOrderDetailArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"订单详情";
    _isShow = NO;
    
    _addressManageViewController = [[AddressManageViewController alloc] init];
    _addressManageViewController.delegate = self;
    _addressManageViewController.tableView.allowsSelection = YES;
    _addressManageViewController.isSelect = YES;
    
    [self setTableViewUI];
    [self setSelectPayMethodsView];
    [self requestShopOrderDetailData];
    
}

-(void)passValue:(AddressManagerDataModel *)model{
    [self.tableView reloadData];
    _addressDataModel = model;
}

-(void)setTableViewUI
{
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
}


-(void)setSelectPayMethodsView{
    self.selectPayMethodView = [[SelectPayMethodsView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //    self.selectPayMethodView.price.text = _total_price
    __weak __typeof(self) weakSelf = self;
    self.selectPayMethodView.hiddenClick = ^{
        [weakSelf hiddenSelectPayMethodsView];
    };
    
    self.selectPayMethodView.doneClick = ^{
        [weakSelf hiddenSelectPayMethodsView];
    };
    [kKeyWindow addSubview:self.selectPayMethodView];
}

- (void)showSelectPayMethodsView
{
    [UIView animateWithDuration:0.3 animations:^{
        self.selectPayMethodView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        self.selectPayMethodView.shadowBtn.alpha = 1;
    }];
}

- (void)hiddenSelectPayMethodsView{
    self.selectPayMethodView.shadowBtn.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        self.selectPayMethodView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

-(void)requestShopOrderDetailData
{
    WeakObj(self);
    NSString *url = [NSString stringWithFormat:@"%@app/mall_order_detail",REQUESTHEADER];
    NSDictionary *dict = @{@"id":@(self.order_id),@"token":[FPLoginAndRegisterTools getToken]};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSDictionary * dic = successResponse;
        NSString *status = [NSString stringWithFormat:@"%@",dic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSError *error;
            selfWeak.shopOrderDetailModel = [[ShopOrderDetailModel alloc] initWithDictionary:dic[@"data"] error:&error];
            [selfWeak.shopOrderDetailArray addObject:selfWeak.shopOrderDetailModel];
            [selfWeak.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2 || section == 3) {
        return 2;
    }else if (section == 1) {
        if (!_isShow) {
            return 1;
        }
        return 1 + 5;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
//        订单状态（0：已取消， 1：待付款， 2：待发货，3：待收货，4：待评价，5：已完成，6：售后中，7：售后完成，）
        NSString *titleStr = @"";
        if ([self.order_status isEqualToString:@"0"]) {
            titleStr = @"订单已取消";
        }else if ([self.order_status isEqualToString:@"1"]){
            titleStr = @"订单已生成,立即付款";
        }else if ([self.order_status isEqualToString:@"2"]){
            titleStr = @"等待卖家发货";
        }else if ([self.order_status isEqualToString:@"3"]){
            titleStr = @"卖家已发货";
        }else if ([self.order_status isEqualToString:@"4"]){
            titleStr = @"已确认收货，待评价";
        }else if ([self.order_status isEqualToString:@"5"]){
            titleStr = @"订单已完成";
        }else if ([self.order_status isEqualToString:@"6"]){
            titleStr = @"售后中";
        }else {
            if ([self.order_status isEqualToString:@"7"]){
                titleStr = @"售后已完成";
            }
        }
        OrderStateTableViewCell *cell = [OrderStateTableViewCell cellWithTableView:tableView andIndexPath:indexPath andTitle:titleStr];
        return cell;
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            static NSString *cellId = @"logisticsCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            }
            for (UIView *subView in cell.subviews) {
                [subView removeFromSuperview];
            }
            UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(22), ScreenX375(18))];
            [cell addSubview:icon];
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(45), ScreenX375(16), ScreenX375(70), ScreenX375(16))];
            noteLabel.text = @"物流信息";
            noteLabel.font = Kfont(14);
            [cell addSubview:noteLabel];
            
            UIImageView *directIcon = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(25), ScreenX375(21), ScreenX375(12), ScreenX375(7))];
            directIcon.image = ImageWithName(@"上拉");
            [cell addSubview:directIcon];
            
            UIView *line = [[UIView alloc] init];
            
            if (_isShow) {
                cell.backgroundColor = ThemeColor;
                cell.accessoryType = UITableViewCellAccessoryNone;
                icon.image = ImageWithName(@"物流信息");
                noteLabel.textColor = [UIColor whiteColor];
                directIcon.hidden = NO;
            }else {
                cell.backgroundColor = [UIColor whiteColor];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                icon.image = ImageWithName(@"物流信息2");
                noteLabel.textColor = FONTCOLOR_BLACK;
                directIcon.hidden = YES;
                
                line.frame = CGRectMake(0, ScreenX375(48) - 0.5, SCREEN_WIDTH, 0.5);
                line.backgroundColor = LineColor;
                [cell addSubview:line];
            }
            
            if ([self.order_status isEqualToString:@"0"] || [self.order_status isEqualToString:@"1"] || [self.order_status isEqualToString:@"2"]) {
                noteLabel.hidden = YES;
                icon.hidden = YES;
                line.hidden = YES;
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
            
            return cell;
        }else if (indexPath.row == 5) {
            static NSString *cellId = @"hiddenCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(11) - 0.5, SCREEN_WIDTH, 0.5)];
                line.backgroundColor = LineColor;
                [cell addSubview:line];
                
                UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(22)) / 2, 0, ScreenX375(22), ScreenX375(22))];
                [sureBtn setImage:ImageWithName(@"上拉") forState:UIControlStateNormal];
                [sureBtn setBackgroundImage:ImageWithName(@"组3") forState:UIControlStateNormal];
                [sureBtn addTarget:self action:@selector(hidden) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:sureBtn];
                
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(37), SCREEN_WIDTH, ScreenX375(10))];
                view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
                [cell addSubview:view];
            }
            return cell;
        }else {
            LogisticsTableViewCell *cell = [LogisticsTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
            if (indexPath.row == 1) {
                [cell setStatu:YES];
            }else {
                [cell setStatu:NO];
            }
            return cell;
        }
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            AddressMessageCell *cell = [AddressMessageCell cellWithTableView:tableView andIndexPath:indexPath];
            if (self.shopOrderDetailArray.count > 0) {
                cell.shopOrderDetailModel = self.shopOrderDetailArray[0];
            }
            if (_addressDataModel) {
                cell.addressManagerDataModel = self.addressDataModel;
            }
            return cell;
        }
        OrderGoodsTableViewCell *cell = [OrderGoodsTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
        if (self.shopOrderDetailArray.count > 0) {
            cell.shopOrderDetailModel = self.shopOrderDetailArray[0];
        }
        return cell;
    }else if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            OrderMessageTableViewCell *cell = [OrderMessageTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
            if (self.shopOrderDetailArray.count > 0) {
                cell.shopOrderDetailModel = self.shopOrderDetailArray[0];
            }
            return cell;
        }else {
            static NSString *cellId = @"operateCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                
                UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(36), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
                sureBtn.backgroundColor = ThemeColor;
                sureBtn.layer.cornerRadius = ScreenX375(22);
                sureBtn.clipsToBounds = YES;
                
                if ([self.order_status isEqualToString:@"0"]) {
                    sureBtn.hidden = YES;
                }else if ([self.order_status isEqualToString:@"1"]){
                    [sureBtn setTitle:@"立即支付" forState:UIControlStateNormal];
                    [sureBtn addTarget:self action:@selector(showSelectPayMethodsView) forControlEvents:UIControlEventTouchUpInside];
                }else if ([self.order_status isEqualToString:@"2"]){
                    [sureBtn setTitle:@"提醒卖家发货" forState:UIControlStateNormal];
                    [sureBtn addTarget:self action:@selector(alertClick) forControlEvents:UIControlEventTouchUpInside];
                }else if ([self.order_status isEqualToString:@"3"]){
                    [sureBtn setTitle:@"确认收货" forState:UIControlStateNormal];
                    [sureBtn addTarget:self action:@selector(sureReciptClick) forControlEvents:UIControlEventTouchUpInside];
                }else if ([self.order_status isEqualToString:@"4"]){
                    [sureBtn setTitle:@"立即评价" forState:UIControlStateNormal];
                    [sureBtn addTarget:self action:@selector(waitCommentClick) forControlEvents:UIControlEventTouchUpInside];
                }else if ([self.order_status isEqualToString:@"5"]){
                    [sureBtn setTitle:@"申请售后" forState:UIControlStateNormal];
                    [sureBtn addTarget:self action:@selector(waitCommentClick) forControlEvents:UIControlEventTouchUpInside];
                }else if ([self.order_status isEqualToString:@"6"]){
                    sureBtn.hidden = YES;
                }else {
                    sureBtn.hidden = YES;
                }
                
                [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                sureBtn.titleLabel.font = Kfont(16);
                [cell addSubview:sureBtn];
            }
            return cell;
        }
    }
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

-(void)alertClick
{
    [HttpManager showNoteMsg:@"已提醒卖家发货"];
}
///确认收货
-(void)sureReciptClick
{
    [self uploadReciptDataWithOrder_id:self.order_id];
}
///立即评价
-(void)waitCommentClick
{
    WaitCommentVC *vc = [[WaitCommentVC alloc] init];
    vc.order_id = self.order_id;
    vc.order_no = self.order_no;
    [self.navigationController pushViewController:vc animated:true];
}

-(void)uploadCancelDataWithOrder_id:(NSInteger)order_id
{
    WeakObj(self);
    NSString *url = [NSString stringWithFormat:@"%@app/order_cancel",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"id":@(order_id),@"state":@(0)};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager showNoteMsg:@"已取消订单"];
            [selfWeak.tableView reloadData];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
        
    }];
}

-(void)uploadReciptDataWithOrder_id:(NSInteger)order_id
{
    WeakObj(self);
    NSString *url = [NSString stringWithFormat:@"%@app/order_cancel",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"id":@(order_id),@"state":@(4)};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager showNoteMsg:@"已确认收货"];
            [selfWeak.tableView reloadData];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        _isShow = !_isShow;
        [_tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 1)] withRowAnimation:UITableViewRowAnimationFade];
    }else{
        if (indexPath.section == 2) {
            if (indexPath.row == 0) {
                [self.navigationController pushViewController:_addressManageViewController animated:true];
            }
        }
    }
}

- (void)hidden {
    _isShow = NO;
    [_tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 1)] withRowAnimation:UITableViewRowAnimationFade];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return ScreenX375(94);
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            if ([self.order_status isEqualToString:@"0"]) {
                return 0.01;
            }else if ([self.order_status isEqualToString:@"1"]){
                return 0.01;
            }else if ([self.order_status isEqualToString:@"2"]){
                return 0.01;
            }else if ([self.order_status isEqualToString:@"3"]){
                return ScreenX375(48);
            }else if ([self.order_status isEqualToString:@"4"]){
                return ScreenX375(48);
            }else if ([self.order_status isEqualToString:@"5"]){
                return ScreenX375(48);
            }else if ([self.order_status isEqualToString:@"6"]){
                return ScreenX375(48);
            }else {
                return ScreenX375(48);
            }
        }else if (indexPath.row == 5) {
            return ScreenX375(47);
        }
        return ScreenX375(64);
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            return ScreenX375(66);
        }
        return ScreenX375(282);
    }else {
        if (indexPath.row == 0) {
            return ScreenX375(140);
        }
        return ScreenX375(116);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0 || section == 2) {
        return ScreenX375(10);
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0 || section == 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
        view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
        return view;
    }
    return nil;
}

@end
